package utils;




import dto.ConfDto;
import org.yaml.snakeyaml.Yaml;


import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件操作工具类
 * Created by cxland on 2017/10/9.
 */
public class FileUtils {
    /**
     *  判断文件是否存在
     * @param path
     * @return
     */
    public static Boolean testFileExist(String path){
        File file = new File(path);
        if(file.exists()){
            return true;
        }
        return false;
    }
    /**
     * 写文件
     * @param path
     * @param fileName
     * @param code
     * @throws IOException
     */
    public static void writeJavaFile (String path,String fileName,String code) throws IOException{
        //  System.out.println("生成路径："+path+"/"+fileName);
        FileWriter     fw = null;
        BufferedWriter bw = null;
        try{
            File dir = new File(path);
            if (!dir.exists()){
                dir.mkdirs();
            }
            File file = new File(dir,fileName);
            if(!file.exists()){
                file.createNewFile();
            }

            fw = new FileWriter(file);
            bw = new BufferedWriter(fw);
            bw.write(code);
            bw.flush();
            bw.close();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if( fw != null){fw.close();}
            if( bw != null){bw.close();}
        }
    }


    public static Boolean readFile(String filePath,String table, String packageName){
        File file = new File(filePath);
        Boolean isTrue = true;
        try {
            if(testFileExist(filePath)){
                FileInputStream input = new FileInputStream(file);
                Writer writer = new FileWriter(file);
                Yaml yaml = new Yaml();
                //读
                ConfDto dto =  yaml.loadAs(input,ConfDto.class);
                Map<String,String> map = dto.getPackageConf();
                map.put(table+"_package",packageName);
                dto.setPackageConf(map);
                System.out.println("写文件");
                yaml.dump(dto, writer);
            }else {
                isTrue = false;
            }
        }catch (IOException E){
            isTrue = false;
        }

       return isTrue;
    }
}
